import { createRouter, createWebHistory ,createWebHashHistory} from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useChatStore } from '@/utils/chat'
import { initializeTokenManager, stopTokenManager } from '@/utils/tokenManager'
import ProductListView from '../views/ProductListView.vue'
import ProductDetailView from '../views/ProductDetailView.vue'
import ProductCreateView from '../views/ProductCreateView.vue'
import ProductUpdateView from '../views/ProductUpdateView.vue'
import UserProfileView from '../views/UserProfileView.vue'
import LoginView from '../views/LoginView.vue'
import RegisterView from '../views/RegisterView.vue'
import ChatMainView from '../views/ChatMainView.vue'
import { authService } from '@/services/apiService'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: ProductListView,
    },
    {
      path: '/product/:id',
      name: 'product-detail',
      component: ProductDetailView,
    },
    {
      path: '/create',
      name: 'product-create',
      component: ProductCreateView,
    },
    {
      path: '/update/:id',
      name: 'product-update',
      component: ProductUpdateView,
    },
    {
      path: '/profile',
      name: 'user-profile',
      component: UserProfileView,
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterView,
    },
    {
      path: '/chat',
      name: 'chat',
      component: ChatMainView,
    },
    // {
    //   path: '/chat/:id',
    //   name: 'chat-detail',
    //   component: ChatMainView,
    // },
    {
    path: '/static-test',
    name: 'static-test',
    component: () => import('@/views/staticView4test.vue'),
    meta: { layout: 'none' }
    },
  ],
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  const chatStore = useChatStore()
  // 尝试从 localStorage 恢复登录状态
  if (!userStore.isLogin) {
    const refresh = localStorage.getItem('refresh')
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || 'null')

    if (refresh && userInfo) {
      try {
        const response = await authService.refresh_token(refresh)
        const access = response.access
        if (access) {
          userStore.isLoggedIn = true
          userStore.userInfo = { access, refresh, ...userInfo }
          chatStore.initializeUnreadTracking()
          
          // 初始化token管理器
          initializeTokenManager(refresh)
        } else {
          throw new Error('Invalid refresh token')
        }
      } catch (error) {
        console.warn('Token refresh failed, clearing auth data')
        stopTokenManager()

        localStorage.removeItem('refresh')
        localStorage.removeItem('access')
        localStorage.removeItem('userInfo')

        userStore.isLoggedIn = false
        chatStore.stopUnreadPolling()
      }
    }
  } else {
    // 用户已登录，确保token管理器已初始化
    const refresh = localStorage.getItem('refresh')
    if (refresh) {
      initializeTokenManager(refresh)
    }
  }
  
   if (userStore.isLogin && !chatStore.isLogin) {
    // 用户刚登录，开始聊天未读数轮询
    chatStore.initializeUnreadTracking()
  } else if (!userStore.isLogin && chatStore.isLogin) {
    // 用户刚登出，停止聊天轮询
    chatStore.stopUnreadPolling()
    stopTokenManager()
  }
  chatStore.setChatPageActive(to.path === '/chat')
  
  // 需要登录的页面
  const protectedRoutes = ['product-create', 'product-update', 'user-profile']

  if (protectedRoutes.includes(to.name as string) && !userStore.isLogin) {
    // 未登录且访问受保护页面，重定向到登录页
    next('/login')
  } else if (userStore.isLogin && (to.name === 'login' || to.name === 'register')) {
    // 已登录且访问登录/注册页，重定向到首页
    next('/')
  } else {
    // 其他情况放行
    next()
  }
})

// 在路由切换后清理资源
router.afterEach((to, from) => {
  // 如果用户登出了，停止token管理器
  const userStore = useUserStore()
  if (!userStore.isLogin) {
    stopTokenManager()
  }
})

export default router